import utility
import re
import collections
import os


class MetadataAttributes:

    def missed_sip(self, data):
        dictionary = collections.OrderedDict()
        sip = re.findall(" - sip.request.header.from=(.*)\n - sip.request.header.to=(.*)\n Pkt: (\d*) \(\d* \w*\), Conn: \d*\(\d*\), App: SIP \(\w*\), State: \w*?, Stack: /ETH/IP/TCP/SIP, Error: \w*", data, flags=0)
        for sipHost in sip:
            print sipHost
            pktNum = "Pkt: " + sipHost[2]
            toHost = "To: " + sipHost[0]
            fromHost = "From: " + sipHost[1]
            toAndFrom = sipHost[0] + sipHost[1]
            if not toAndFrom in dictionary:
                dictionary[toAndFrom] = "{: <15}{}\n\t\t{}\n\n".format(pktNum, toHost, fromHost)
        return dictionary.values()

    def missed_attributes(self, file_path):
        if str(file_path).endswith(".pkt.log"):
            output_path = file_path + ".metadata.log"
            lines = []
            with open(output_path, 'w+') as output:
                output.write(file_path + "\n")
                lines.append(file_path + "\n")
                with open(file_path, 'r') as f:
                    output.write("SIP:\n")
                    lines.append("SIP:\n")
                    output.write("\n")
                    lines.append("\n")
                    data = f.read()
                    sipHostList = self.missed_sip(data)
                    for host in sipHostList:
                        output.write(host)
                        lines.append(str(host))
                    output.write("\n")
                    lines.append("\n")
                f.close()
            output.close()
            return lines

    def metadata_folder(self, directory, output_path):
        if os.path.isdir(directory):
            try:
                files = utility.Directory(directory, ".pkt.log")
                print "Total number of files is: %s" % str(files.count())
                print type(files)
                with open(output_path, 'w+') as output:
                    for f in files:
                        dataList = self.missed_attributes(f)
                        print f + "\t" + files.percentage(f)
                        if dataList:
                            for item in dataList:
                                output.write(item)
                output.close()
            except Exception, error_msg: print error_msg
        else: print "Not a directory: %s" % directory